package gui;

import model.Model;

import javax.swing.*;

import gui.image.ImageComponent;
import util.Config;

import java.awt.*;
import java.awt.event.MouseMotionAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseAdapter;

public class ImagePanel extends JPanel {

    private final Model model;

    private boolean editable = false;

    private ImageComponent image;

    public ImagePanel(final Model model) {
        this.model = model;
        final Config config = Config.getInstance();
        Dimension d = new Dimension(config.getImageWidth(), config.getImageHeight());
        setPreferredSize(d);
        setSize(d);
        addMouseListener(new MouseAdapter() {

            private int x;

            private int y;

            private boolean isValidX(int x) {
                return (x >= 0) && (x < config.getImageWidth());
            }

            private boolean isValidY(int y) {
                return (y >= 0) && (y < config.getImageHeight());
            }

            public void mouseReleased(MouseEvent e) {
                if (editable) {
                    int dx = e.getX() - image.getX() - x;
                    int dy = e.getY() - image.getY() - y;
                    if (isValidX(x) && isValidY(y) && isValidX(x + dx) && isValidY(y + dy)) {
                        model.imageChangeFromGUI(getID(), x, y, dx, dy);
                    }
                }
            }

            @Override
            public void mousePressed(MouseEvent e) {
                if (editable) {
                    x = e.getX() - image.getX();
                    y = e.getY() - image.getY();
                }
            }

        });
    }

    public void update(int id) {
        Config config = Config.getInstance();
        removeAll();
        if (id != -1) {
            image = new ImageComponent(model.getImage(id), config.getImageWidth(), config.getImageHeight(), id);        
            add(image);
        }
        revalidate();
        repaint();
    }

    public int getID() {
        if (image != null) {
            return image.getID();
        } else {
            return -1;
        }
    }

    public void setEditable(boolean flag) {
        editable = flag;
    }

}